/**
 * CMCCDataSource.java
 * Jan 9, 2010
 */
package com.dlplay.flightinfo.source;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import com.dlplay.flightinfo.data.AirFlightCode;
import com.dlplay.flightinfo.data.Airport;
import com.dlplay.flightinfo.data.AirportTerminalCode;
import com.dlplay.flightinfo.data.Flight;
import com.dlplay.flightinfo.data.RealTimeFlightInfo;
import com.dlplay.flightinfo.data.Weather;

/**
 * @author zhang yu
 *
 */
public class CMCCDataSource extends DataSource
	implements RealTimeFlightDS,AirportDataSource{
	
	private static final Logger log = Logger.getLogger(CMCCDataSource.class.getName());
	//DataSource priority 0~9 low to high
	private static final String CMCC_WEATHER_INFO = "http://www.12580.hk/weather/index.php?action=getweather&city=";
	public static final int DEFAULT_DATASOURCE_PRI = 8;
	/* (non-Javadoc)
	 * @see com.dlplay.flightinfo.core.datasource.DataSource#getAirportByName()
	 */
	@Override
	public Airport getAirport(AirportTerminalCode code) {
		// TODO Auto-generated method stub

		Airport airport = new Airport();
		airport.setIdentifier(code);
		airport.setWeather(new Weather());
		String temp;

		//Try to get the airport information
		try {
			log.log(Level.INFO,"in processSubmit code " + code);
			
			//OK, now we need to perform the url fetch

			URL url = new URL(CMCC_WEATHER_INFO + getName(code));
			log.log(Level.INFO,"in processSubmit URL url = ", url);
			
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            //we need to set the http header property
//            connection.setDoOutput(true);
//            connection.setDoInput(true);
//            connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
//            connection.setRequestProperty("use_intranet", "true");
            connection.setRequestMethod("GET");
            //set connection timeout to maximum 10
            connection.setConnectTimeout(95000); 
            connection.connect();
            
            //TODO Do we need to get length
            int length = connection.getContentLength();
            log.log(Level.INFO,"processSubmit: length " + length);
            
            //connection.getContent();
            //using html parser to parse the html
            log.log(Level.INFO,"in processSubmit Source source=new Source");
            Source source=new Source(new InputStreamReader(connection.getInputStream(), "utf-8"));
            Element divWeather = source.getElementById("WeatherList");
            
//          <div id="WeatherList">
//          <div class="list"> 
//			<ul style="width:100px;padding-top:23px;height:38px;">1月10日星期日</ul> 
//			<ul style="width:69px;"> 
//                <li class="two" style="height:25px;padding-top:5px">白天</li> 
//                <li style="height:25px;padding-top:5px">夜间</li> 
//            </ul> 
//            
//			<ul style="width:69px;"> 
//                <li class="two" style="height:25px;padding-top:5px"><img src="../images/weather/d02.gif" /></li> 
//                <li style="height:25px;padding-top:5px"><img src="../images/weather/n00.gif" /></li>                          
//            </ul> 
//			<ul style="width:100px;"> 
//                <li class="two" style="height:25px;padding-top:5px">阴</li> 
//                <li style="height:25px;padding-top:5px">晴</li>                        
//            </ul> 
//			<ul style="width:101px;"> 
//				<li class="two" style="height:25px;padding-top:5px">高温 -3℃</li> 
//				<li style="height:25px;padding-top:5px">低温 -10℃</li> 
//            </ul> 
//            
//			<ul style="width:101px;"> 
//				<li class="two" style="height:25px;padding-top:5px">无持续风向</li> 
//				<li style="height:25px;padding-top:5px">北风</li> 
//            </ul> 
//            
//			<ul style="width:101px;"> 
//                <li class="two" style="height:25px;padding-top:5px">微风</li> 
//				<li style="height:25px;padding-top:5px">3-4级</li> 
//            </ul> 
//            </div>  
//            </div>
            
            if (divWeather != null)
            {
            	List<Element> elements = divWeather.getAllElements(HTMLElementName.UL);
            	//elements.remove(0);
            	//所在位置：
            	
            	//0. <ul style="width:100px;padding-top:23px;height:38px;">1月10日星期日</ul> 
            	//2. 
            	
            	//3 <ul style="width:100px;"> 
//		              <li class="two" style="height:25px;padding-top:5px">阴</li> 
//		              <li style="height:25px;padding-top:5px">晴</li>                        
//		          </ul> 
            	temp = elements.get(3).getAllElements().get(1).getTextExtractor().toString();
            	//temp = 阴
            	//String tempWeather = temp.substring(temp.indexOf("：") + 1);
            	airport.getWeather().setWeather(temp);
            	String temp1 = elements.get(3).getAllElements().get(2).getTextExtractor().toString();
            	if (!temp1.equals(temp))
            	{
            		airport.getWeather().setWeather(airport.getWeather().getWeather() + "转" + temp1);
            	}
            	
            	//4 <ul style="width:101px;"> 
//				<li class="two" style="height:25px;padding-top:5px">高温 -3℃</li> 
//				<li style="height:25px;padding-top:5px">低温 -10℃</li> 
//            </ul>             	temp = elements.get(4).getFirstElement().getTextExtractor().toString();
            	temp = elements.get(4).getAllElements().get(1).getTextExtractor().toString();
            	airport.getWeather().setTemperatureHigh(new Integer(temp.substring(temp.indexOf(" ") + 1, temp.indexOf("℃")).trim()));
            	temp = elements.get(4).getAllElements().get(2).getTextExtractor().toString();
            	airport.getWeather().setTemperatureLow(new Integer(temp.substring(temp.indexOf(" ") + 1, temp.indexOf("℃")).trim()));
            	
            	//6 <ul style="width:101px;"> 
//                <li class="two" style="height:25px;padding-top:5px">微风</li> 
//				<li style="height:25px;padding-top:5px">3-4级</li> 
//            </ul>             	
            	temp = elements.get(6).getAllElements().get(2).getTextExtractor().toString();
            	airport.getWeather().setWind(temp);
            	
            	airport.getWeather().setTemperatureNow(
            			(airport.getWeather().getTemperatureHigh() + airport.getWeather().getTemperatureLow())/2);
            	
            	
            	//Get Airport name changed to UTF-8
            	Element input = source.getElementById("city");
            	airport.setIdentifier(getCode(input.getAttributeValue("value")));
            	//airport.setName(input.getAttributeValue("value"));
                
            	//TODO 24-hours forcast
            	
            	//OK, now we need to reture the info
            	return airport;
            	
            }

		}catch (MalformedURLException e) {
            // ...
        	e.printStackTrace();
        	log.log(Level.WARNING,"in processSubmit MalformedURLException");
			return null;
        	
        } catch (IOException e) {
            // ...
        	e.printStackTrace();
        	log.log(Level.WARNING,"in processSubmit IOException");
			return null;
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.log(Level.WARNING,e.getMessage());
		}
		return null;
	}

	private static final AirportTerminalCode getCode(String attributeValue) {
		// TODO real change		
		return AirportTerminalCode.PEK_T1;
	}

	private static final String getName(AirportTerminalCode code) {
		//TODO real change
		return "Beijing";
	}

	/* (non-Javadoc)
	 * @see com.dlplay.flightinfo.core.datasource.DataSource#getFlightByNum()
	 */
	@Override
	public RealTimeFlightInfo getFlightByNum(AirFlightCode flightNum){
		// TODO Auto-generated method stub
		return null;
	}

}
